<template>
  <div class="app-container">    
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <div class="flex input-height">
        <div class="label" v-if="deptId==101">收费站：</div>
        <div class="align-center" v-if="deptId==101">
          <el-tree-select v-model="queryParams.deptId" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
            class="margin-right" placeholder="请选择部门" check-strictly clearable @change="bindChangeTree($event,'deptId')" />
        </div>
        <div class="label">时间：</div>
        <div class="align-center">
          <el-radio-group v-model="cycleRadio" @change="bindchangeDate" class="margin-right">
            <el-radio-button label="day" v-if="radioIndex!='3'&&radioIndex!='4'">本日</el-radio-button>
            <el-radio-button label="week" v-if="radioIndex!='3'&&radioIndex!='4'">本周</el-radio-button>
            <el-radio-button label="month">本月</el-radio-button>
            <el-radio-button label="season">本季</el-radio-button>
            <el-radio-button label="year">本年</el-radio-button>
          </el-radio-group>
          <el-date-picker style="margin-right:8px" v-model="dateSection" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
            @change="bindChangeAllDate" />
        </div>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </div>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="[route.query.type==1?'audit:stat_ycbq:add':route.query.type==2?'audit:stat_dcxb:add':route.query.type==3?'audit:stat_sfzzj:add':route.query.type==4?'audit:stat_zzjlxzryh:add':'audit:stat_lstdyh:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport(4)" v-hasPermi="['audit:stat_dcxb:import']" v-if="route.query.type==4">导入</el-button>
        <el-button type="info" plain icon="Upload" @click="handleImport(5)" v-hasPermi="['audit:stat_dcxb:import']" v-if="route.query.type==5">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="[route.query.type==1?'audit:stat_ycbq:export':route.query.type==2?'audit:stat_dcxb:export':route.query.type==3?'audit:stat_sfzzj:export':route.query.type==4?'audit:stat_zzjlxzryh:export':'audit:stat_lstdyh:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <Custable :loading="loading" :content="goOutContent" :list="tableData" :queryParams="queryParams" :total="total" @getList="getList">
      <template #operation="scope">
        <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
          v-hasPermi="[route.query.type==1?'audit:stat_ycbq:edit':route.query.type==2?'audit:stat_dcxb:edit':route.query.type==3?'audit:stat_sfzzj:edit':route.query.type==4?'audit:stat_zzjlxzryh:edit':'audit:stat_lstdyh:edit']">修改</el-button>
        <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
          v-hasPermi="[route.query.type==1?'audit:stat_ycbq:remove':route.query.type==2?'audit:stat_dcxb:remove':route.query.type==3?'audit:stat_sfzzj:remove':route.query.type==4?'audit:stat_zzjlxzryh:remove':'audit:stat_lstdyh:remove']">删除</el-button>
      </template>
    </Custable>

    <Mask v-if="dialogVisible" :dialogVisible="dialogVisible" @handleClose="handleClose" :queryParams="queryParams" :rowDetails="rowDetails" :rules="rules" :title="title"
      :interface="carTypeList[radioIndex].interface" :formItemConfig="formItemConfig" />


          <!-- 导入对话框 -->
    <el-dialog title="导入" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import moment from 'moment'
import { listStat_ycbq, getStat_ycbq, delStat_ycbq } from "@/api/charge/stat_ycbq";
import { listStat_dcxb, getStat_dcxb, delStat_dcxb } from "@/api/charge/stat_dcxb";
import { listStat_sfzzj, getStat_sfzzj, delStat_sfzzj } from "@/api/charge/stat_sfzzj";
import { listStat_zzjlxzryh, getStat_zzjlxzryh, delStat_zzjlxzryh } from "@/api/charge/stat_zzjlxzryh";
import { listStat_lstdyh, getStat_lstdyh, delStat_lstdyh } from "@/api/charge/stat_lstdyh";
import { deptTreeSelect } from "@/api/system/user";
import useUserStore from '@/store/modules/user'
import Custable from "@/components/Custom/Custable";
import Mask from "./components/Mask";
import config from "./config"
import { ref, watch } from 'vue';
import { getToken } from "@/utils/auth";
const { proxy } = getCurrentInstance()
const userStore = useUserStore()
const route = useRoute();
const { audit_in_out } = proxy.useDict('audit_in_out');
const queryParams = ref({ "startDate": '', "endDate": '', pageNum: 1, pageSize: 10 })
const radioCarCon = ref('异常标签稽核台账')
const carTypeList = ref([
  { label: '异常标签稽核台账', value: "0", interface: 'ycbq' },
  { label: '大车小标逃费车辆追缴纠正统计', value: "1", interface: 'dcxb' },
  { label: '收费站追缴名单车辆限行情况统计', value: "2", interface: 'sfzzj' },
  { label: '仔猪及冷鲜猪肉通行费优惠政策落实', value: "3", interface: 'zzjlxzryh' },
  { label: '绿色通道通行费优惠政策落实', value: "4", interface: 'lstdyh' },
])
const cycleRadio = ref('day')
const dialogVisible = ref(false)
const goOutContent = ref(config.goOutContent1)
const formItemConfig = ref(config.formItemConfig1)
const loading = ref(false)
const deptOptions = ref([])
const tableData = ref([])
const total = ref(0)
const rowDetails = ref({})
const dateSection = ref([])
const radioIndex = ref(0)
const methods = ref({ listStat_ycbq, delStat_ycbq, listStat_dcxb, delStat_dcxb, listStat_sfzzj, delStat_sfzzj, listStat_zzjlxzryh, delStat_zzjlxzryh, listStat_lstdyh, delStat_lstdyh })
const rules = ref(config.rules1)
const deptId = ref()
const title=ref('新增')
/*** 导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/audit/stat_zzjlxzryh/importData"
  //  url: import.meta.env.VITE_APP_BASE_API + radioIndex==3?"/audit/cardError/importData":"/audit/lostAxles/importData"
});
watch(() => audit_in_out.value, (New, Old) => {
  config.formItemConfig3[1].options = New
}, { deep: true, immediate: true })


const bindCarRadio = (name, val, index) => {


  goOutContent.value = config[`goOutContent${(Number(index))}`];
  formItemConfig.value = config[`formItemConfig${(Number(index))}`];
  rules.value = config[`rules${(Number(index))}`];
  radioIndex.value = val;
  tableData.value = [];
  if (index != 4 && index != 5) {
    cycleRadio.value = "day"
    bindchangeDate("day")
  } else {
    cycleRadio.value = "month"
    bindchangeDate("month")
  }
  // getList('listStat_' + carTypeList.value[val].interface)
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
    config.formItemConfig1[0].options = deptOptions.value;
    config.formItemConfig1[1].options = deptOptions.value;
    config.formItemConfig2[0].options = deptOptions.value;
    config.formItemConfig2[1].options = deptOptions.value;
    config.formItemConfig2[2].options = deptOptions.value;
    config.formItemConfig3[0].options = deptOptions.value;
    config.formItemConfig4[0].options = deptOptions.value;
    config.formItemConfig4[1].options = deptOptions.value;
    config.formItemConfig4[2].options = deptOptions.value;
    config.formItemConfig5[0].options = deptOptions.value;
    config.formItemConfig5[1].options = deptOptions.value;
    config.formItemConfig5[2].options = deptOptions.value;
    // rowDetails.value.companyId = deptOptions.value[0].id;

  });
};
/** 查询异常标签稽核台账列表 */
function getList(abutment) {
  loading.value = true;
  methods.value[abutment ? abutment : 'listStat_' + carTypeList.value[route.query.type - 1].interface](queryParams.value).then(response => {
    tableData.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除异常标签稽核台账编号为"' + _ids + '"的数据项？').then(function () {
    return methods.value['delStat_' + carTypeList.value[radioIndex.value].interface](_ids);
  }).then(() => {
    getList('listStat_' + carTypeList.value[radioIndex.value].interface);
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  let url=route.query.type==1?'audit/stat_ycbq/export':route.query.type==2?'audit/stat_dcxb/export':route.query.type==3?'audit/stat_sfzzj/export':route.query.type==4?'audit/stat_zzjlxzryh/export':'audit/stat_lstdyh/export'
  let name=route.query.type==1?'异常标签稽核台账':route.query.type==2?'大车小标逃费车辆追缴纠正统计':route.query.type==3?'收费站追缴名单车辆限行情况统计':route.query.type==4?'仔猪及冷鲜猪肉通行费优惠政策落实':'绿色通道通行费优惠政策落实';
  proxy.download(url, {
    ...queryParams.value
  }, `${name}_${new Date().getTime()}.xlsx`)
}
const bindChangeAllDate = (val) => {
  if (!val) { dateSection.value = []; queryParams.value.startDate = ''; queryParams.value.endDate = ''; return }
  dateSection.value = [moment(val[0]).format("YYYY-MM-DD"), moment(val[1]).format("YYYY-MM-DD")]
  queryParams.value.startDate = dateSection.value[0];
  queryParams.value.endDate = dateSection.value[1];
}

/** 搜索按钮操作 */
function handleQuery() {
  getList('listStat_' + carTypeList.value[radioIndex.value].interface)
};
/** 重置按钮操作 */
function resetQuery() {
 
  proxy.resetForm("queryRef");
  queryParams.value = { pageNum: 1, pageSize: 10,deptId:deptId.value };
  cycleRadio.value = "day";
  init()
  handleQuery();
};
const handleAdd = () => {
  rowDetails.value = {
    deptId: deptId.value,
    entryOrExit: "",
    userId:''
  }
  title.value="新增"
  dialogVisible.value = true;
}
const handleUpdate = (data) => {
  // if (route.query.type == 4 || route.query.type == 5) {
  //   data.month = data.month ? data.year + "-" + data.month : "";
  //   data.year = data.year ? data.year.toString() : "";
  //   console.log(111, data)
  // }
  title.value="修改"
  rowDetails.value = data;
  if(route.query.type == 3){rowDetails.value.entryOrExit=data.entryOrExit.toString()}

  
  dialogVisible.value = true;
}

const handleClose = () => {

  dialogVisible.value = false;
  getList('listStat_' + carTypeList.value[radioIndex.value].interface)
}
const bindchangeDate = (val) => {
  let date = new Date();
  let year = date.getFullYear();
  let params = {}
  if (val == 'day') {
    params.startDate = moment().format("YYYY-MM-DD")
    params.endDate = moment().format("YYYY-MM-DD");
  } else if (val == 'week') {
    params.startDate = moment().startOf('week').format('YYYY-MM-DD');
    params.endDate = moment().endOf('week').format('YYYY-MM-DD')
  } else if (val == 'month') {

    params.startDate = moment().startOf('month').format('YYYY-MM-DD');
    params.endDate = moment().endOf('month').format('YYYY-MM-DD')
  } else if (val == 'season') {
    let startQuarter = moment(moment().quarter(moment().quarter()).startOf('quarter').valueOf()).format('YYYY-MM-DD');
    let endQuarter = moment(moment().quarter(moment().quarter()).endOf('quarter').valueOf()).format('YYYY-MM-DD');
    params.startDate = startQuarter
    params.endDate = endQuarter
  } else {
    params.startDate = year + '-01-01'
    params.endDate = year + '-12-31'
  }
  dateSection.value = [moment(params.startDate).format("YYYY-MM-DD"), moment(params.endDate).format("YYYY-MM-DD")]
  queryParams.value = { ...queryParams.value, ...params,deptId:deptId.value};
  getList('listStat_' + carTypeList.value[radioIndex.value].interface)


}
const bindChangeTree = (val, name) => {
  queryParams.value[name] = val;
}
const getDeptId = () => {
  userStore.getInfo().then(res => {
    if (res.code == 200) {
      deptId.value = res.user.dept.deptId;
      rowDetails.value.deptId = deptId.value;

      queryParams.value.deptId = deptId.value
      if (route.query) {
        bindCarRadio(carTypeList.value[route.query.type - 1].label, route.query.type - 1, route.query.type)
      }
    }

  })
}
/** 导入按钮操作 */
function handleImport(type) {
  if (type == 4) {
    upload.url = import.meta.env.VITE_APP_BASE_API + "/audit/stat_zzjlxzryh/importData"
  } else {
    upload.url = import.meta.env.VITE_APP_BASE_API + "/audit/stat_lstdyh/importData"
  }
  upload.open = true
}
/** 下载模板操作 */
function importTemplate() {

  let url = route.query.type == 4 ? "audit/stat_zzjlxzryh/importTemplate" : "/audit/stat_lstdyh/importTemplate"
  proxy.download(url, {
  }, `template_${new Date().getTime()}.xlsx`);
};
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};


const init = () => {
  let startDate = moment().format("YYYY-MM-DD");
  dateSection.value = [startDate, startDate]
  queryParams.value.startDate = startDate;
  queryParams.value.endDate = startDate;


}
init()
getDeptTree()
getDeptId()

</script>

<style scoped>
.flex {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.flex .label {
  color: #333;
  font-size: 14px;
}

/deep/.padding .el-radio-button--large .el-radio-button__inner {
  padding: 8px 19px;
}
/deep/ .custom-tag .el-radio-button--large .el-radio-button__inner {
  min-width: 60px;
  height: 32px;
  line-height: 32px;
  margin: 0 4px 0;
  padding: 0 10px;
  border: 1px solid #e4e4e4;
  font-size: 14px;
}
/deep/ .custom-tag .el-radio-button--large.is-active .el-radio-button__inner {
  background: #fff;
  border: 1px solid #246bcc;
  color: #246bcc;
  position: relative;
}

/deep/
  .custom-tag
  .el-radio-button--large.is-active
  .el-radio-button__inner:after {
  content: "";
  position: absolute;
  top: 0px;
  right: 0px;
  border-top: 20px solid #246bcc;
  border-left: 20px solid transparent;
}
/deep/
  .custom-tag
  .el-radio-button--large.is-active
  .el-radio-button__inner:before {
  content: "";
  position: absolute;
  width: 5px;
  height: 6px;
  background: transparent;
  top: 2px;
  right: 4px;
  border: 1px solid white;
  border-top: none;
  border-right: none;
  transform: rotate(-55deg);
  z-index: 9;
}

.margin-right {
  margin-right: 8px;
}
/deep/ .input-height .el-input__wrapper {
  height: 32px;
}
/deep/ .input-height .el-date-editor.el-input {
  height: 32px;
}
.margin-right-lg {
  margin-right: 32px;
}
.cursor {
  cursor: pointer;
}
.flex-end {
  margin-left: auto;
}
.active {
  position: relative;
}
.active::before {
  content: "";
  display: block;
  width: 50px;
  height: 2px;
  border-radius: 2px;
  background: var(--el-color-primary);
  position: absolute;
  bottom: 3px;
  left: 50%;
  transform: translateX(-50%);
}

.align-center {
  display: flex;
  align-items: center;
}
</style>